package com.duolaibei.business.view.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.duolaibei.business.R;
import com.duolaibei.business.base.BaseActivity;
import com.duolaibei.business.config.Preferences;
import com.duolaibei.business.utils.BluetoothUtil;
import com.duolaibei.business.utils.CommonUtil;
import com.duolaibei.business.utils.PreferenceUtil;
import com.duolaibei.business.utils.inject.Inject;
import com.duolaibei.business.utils.log.LogDebug;
import com.duolaibei.business.widget.ToggleButton;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by xlm on 2017/11/11 0011
 */

public class BluetoothPrintActivity extends BaseActivity {
    @Inject(R.id.back)
    private RelativeLayout mLayoutBack;
    @Inject(R.id.title)
    private TextView mViewTitle;
    @Inject(R.id.toogle_button)
    private ToggleButton mToggleButton;
    @Inject(R.id.bluetooth_num)
    private TextView mTextViewBlueNum;//蓝牙数目
    @Inject(R.id.reset_search)
    private TextView mTextViewResetSearch;//重新搜索

    @Inject(R.id.bluetooth_recycle)
    private RecyclerView mRecyclePrintNum;

    private List<BluetoothBean> mBlueList;//打印机名称列表
    private Set<BluetoothBean> mBlueDiscoveryList;//扫描列表
    private CommonAdapter<BluetoothBean> mCommonAdapter;
    private BluetoothAdapter mBluetoothAdapter = null;
    private boolean isScan = true;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_bluetooth_print);
    }

    @Override
    protected void initViews() {
        mViewTitle.setText("蓝牙打印机");
    }

    @Override
    public void beforeOnCreate() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mBlueDiscoveryList = new HashSet<>();
        mBlueList = new ArrayList<>();
        setBluetoothAdapter();
        registBlueFoundReceiver();//注册广播 获取新的蓝牙
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        if (mBluetoothAdapter != null) {
            if (mBluetoothAdapter.isEnabled()) {
                if (isScan) {
                    doDiscovery();
                }
                mToggleButton.setToggleOn();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (BluetoothUtil.connectBlueTooth(getThis())) {
                            getBondsDevice(true);
                            PreferenceUtil.setParam(Preferences.ISCONNECTED, "true");
                        } else {
                            getBondsDevice(false);
                            PreferenceUtil.setParam(Preferences.ISCONNECTED, "false");
                        }
                    }
                }).start();
            } else {
                mToggleButton.setToggleOn();
                //打开蓝牙，需要BLUETOOTH_ADMIN权限
                mBluetoothAdapter.enable();
            }
        }
    }

    /**
     * 注册蓝牙发现或者未找到设备的广播
     */
    private void registBlueFoundReceiver() {
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, filter);//发现新设备
        filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        this.registerReceiver(mReceiver, filter);//蓝牙开闭状态
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mReceiver, filter);//搜索结果
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {//发现新设备
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    String mac = String.valueOf(device.getAddress());
                    String name = String.valueOf(device.getName());
                    if (!CommonUtil.isEmpty(name) && !CommonUtil.isEmpty(mac)) {
                        BluetoothBean bluetoothBean = new BluetoothBean();
                        bluetoothBean.setMac(mac);//设置蓝牙mac
                        bluetoothBean.setName(name);//设置蓝牙名称
                        bluetoothBean.setState("0");//设置状态
                        mBlueDiscoveryList.add(bluetoothBean);
                    }
                }
            } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                switch (blueState) {
                    case BluetoothAdapter.STATE_ON:
                        LogDebug.d("---------STATE_ON--------");
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if (BluetoothUtil.connectBlueTooth(getThis())) {
                                    PreferenceUtil.setParam(Preferences.ISCONNECTED, "true");
                                    getBondsDevice(true);
                                } else {
                                    PreferenceUtil.setParam(Preferences.ISCONNECTED, "false");
                                    getBondsDevice(false);
                                }
                                doDiscovery();
                            }
                        }).start();
                        break;
                    case BluetoothAdapter.STATE_OFF:
                        LogDebug.d("---------STATE_OFF--------");
                        if (mBlueDiscoveryList.size() != 0) {
                            mBlueDiscoveryList.clear();
                        }
                        PreferenceUtil.setParam(Preferences.ISCONNECTED, "false");
                        break;
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                if (mBluetoothAdapter != null) {
                    //蓝牙打开状态
                    if (mBluetoothAdapter.isEnabled()) {
                        //扫描结束
                        if (mBlueDiscoveryList.size() != 0) {
                            showToast("扫描完成");
                            mBlueList.addAll(mBlueDiscoveryList);
                            mTextViewBlueNum.setText(String.valueOf(mBlueList.size()));
                            onRefreshData();
                            mBlueDiscoveryList.clear();
                        }
                    }
                }
            }
        }
    };

    /**
     * 获取配对设备
     */
    private void getBondsDevice(boolean success) {
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        BluetoothBean bluetoothBean;
        if (mBlueList.size() != 0) {
            mBlueList.clear();
        }
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice devices : pairedDevices) {
                bluetoothBean = new BluetoothBean();
                bluetoothBean.setMac(String.valueOf(devices.getAddress()));//设置蓝牙mac
                bluetoothBean.setName(String.valueOf(devices.getName()));//设置蓝牙名称
                if (success) {
                    if (devices.getAddress().equals(PreferenceUtil
                            .getParam(Preferences.BLUETOOTH, ""))) {
                        bluetoothBean.setState("2");//已连接
                    } else {
                        bluetoothBean.setState("0");//连接
                    }
                } else {
                    bluetoothBean.setState("0");//连接
                }
                mBlueList.add(bluetoothBean);
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mTextViewBlueNum.setText(String.valueOf(mBlueList.size()));
                }
            });
            onRefreshData();
        }

    }

    /**
     * 刷新显示数据
     */
    private void onRefreshData() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mCommonAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 扫描设备
     */
    private void doDiscovery() {
        if (mBluetoothAdapter == null) {
            showToast("您的设备不支持蓝牙");
            return;
        }
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        if (mBlueDiscoveryList.size() != 0) {
            mBlueDiscoveryList.clear();
        }
        mBluetoothAdapter.startDiscovery();
    }

    @Override
    protected void onSetListener() {
        setToogleButton();
        mLayoutBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTextViewResetSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mToggleButton.setToggleOn();
                mBluetoothAdapter.enable();
                isScan = true;
            }
        });
    }

    /**
     * 设置切换btn
     */
    private void setToogleButton() {
        //开关切换事件
        mToggleButton.setOnToggleChanged(new ToggleButton.OnToggleChanged() {
            @Override
            public void onToggle(boolean on) {
                if (!on) {
                    showToast("蓝牙已关闭");
                    if (mBluetoothAdapter != null) {
                        mBluetoothAdapter.cancelDiscovery();
                    }
                    switchBlueTooth(false);//关闭蓝牙
                    if (mBlueList.size() != 0) {
                        mBlueList.clear();
                        onRefreshData();
                    }
                    mTextViewBlueNum.setText("0");
                } else {
                    showToast("蓝牙已打开");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            switchBlueTooth(true);//打开蓝牙
                        }
                    }).start();
                }
            }
        });
    }

    /**
     * 打开或者关闭蓝牙
     */
    private void switchBlueTooth(boolean isChangState) {
        if (!isChangState) {
            isScan = false;
            BluetoothUtil.disconnectBlueTooth(getThis());
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mBluetoothAdapter.disable();//关闭
                }
            }, 2000);
        } else {
            mBluetoothAdapter.enable();//打开
        }
    }

    /**
     * 设置已经配对的蓝牙adapter
     */
    private void setBluetoothAdapter() {
        mBlueList = new ArrayList<>();
        mCommonAdapter = new CommonAdapter<BluetoothBean>(getThis(),
                R.layout.item_print_num, mBlueList) {
            @Override
            protected void convert(final ViewHolder holder,
                                   final BluetoothBean bean, final int position) {
                holder.setText(R.id.print_name, bean.getName());
                final String mac = bean.getMac();
                if ("0".equals(bean.getState())) {
                    holder.setText(R.id.print_connect, "连接");
                    holder.getView(R.id.print_connect).setClickable(true);
                    holder.getView(R.id.print_connect).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //点击设置蓝牙mac地址
                            BluetoothUtil.setMac(mac);
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    if (BluetoothUtil.connectBlueTooth(getThis())) {
                                        PreferenceUtil.setParam(Preferences.BLUETOOTH, mac);
                                        for (BluetoothBean bean : mBlueList) {
                                            if (mac.equals(bean.getMac())) {
                                                bean.setState("2");
                                            } else {
                                                bean.setState("0");
                                            }
                                        }
                                        onRefreshData();
                                    } else {
                                        showToast("连接失败");
                                    }
                                }
                            }).start();
                        }
                    });
                } else if ("1".equals(bean.getState())) {
                    holder.setText(R.id.print_connect, "连接中");
                    holder.getView(R.id.print_connect).setClickable(false);
                } else if ("2".equals(bean.getState())) {
                    holder.setText(R.id.print_connect, "已连接");
                    holder.getView(R.id.print_connect).setClickable(false);
                    PreferenceUtil.setParam(Preferences.ISCONNECTED, "true");
                }
            }
        };
        mRecyclePrintNum.setLayoutManager(new LinearLayoutManager(getThis()));
        mRecyclePrintNum.setAdapter(mCommonAdapter);
    }

    @Override
    protected void onDestroy() {
        this.unregisterReceiver(mReceiver);
        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.cancelDiscovery();
        }
        super.onDestroy();
    }

    private class BluetoothBean {
        String mac;
        String name;
        String state;

        public String getState() {
            return state;
        }

        public void setState(String state) {
            this.state = state;
        }

        public String getMac() {
            return mac;
        }

        public void setMac(String mac) {
            this.mac = mac;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
